package com.hurl.library.schedule;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

class SchedulerImpl implements Scheduler{
	private static final Logger log = Logger.getLogger(SchedulerImpl.class);

	private boolean running = false;
	private JobTrigger trigger = null;
	private static Timer timer = new Timer();
	
	private class TaskRunner extends TimerTask{
		private Job job;
		
		public TaskRunner(Job job){
			this.job = job;
		}
		@Override
		public void run() {
			try{
				log.info("开始执行定时任务“"+job.getDescription()+"” 。。。");
				job.run();
				job.onSuccess();
				log.info("执行定时任务“"+job.getDescription()+"”成功！");
			}catch(Exception e){
				job.onFailure();
				log.info("执行定时任务“"+job.getDescription()+"”成功失败！",e);
			}
		}
	};
	
	/**
	 * task pool
	 */
	private List<Job> jobList = new ArrayList<Job>();
	
	public void start() throws ScheduleException{
		if(this.trigger==null){
			throw new ScheduleException("Job trigger has not been setted!");
		}
		if(this.trigger.getFirstTime()==null){
			throw new ScheduleException("First run time not set!");
		}
		
		if(jobList.isEmpty())
			return;
		
		for(Job job : jobList){
			if(trigger.getPeriod()==null){
				timer.schedule(new TaskRunner(job), trigger.getFirstTime());
			}else{
				timer.scheduleAtFixedRate(new TaskRunner(job), trigger.getFirstTime(),trigger.getPeriod());
			}
		}
		running=true;
	}
	
	public void shutdown(){
		if(jobList.isEmpty())
			return;

		timer.cancel();
		
		running=false;
	}
	
	/**
	 * 获取系统所有的定时任务信息。
	 * @return
	 */
	public List<Job> getJobs(){
		return jobList;
	}
	
	public void addJob(Job task)throws ScheduleException{
		addJob(task, false);
	}

	/**
	 * 添加一个定时任务。
	 * @param task
	 * @throws ScheduleException
	 */
	public void addJob(Job task, boolean disabled)throws ScheduleException{
		//not allowed to add task when schedule is already running.
		if(running){
			throw new ScheduleException("Schedule is already running,please shutdown Scheduler before adding tasks!");
		}
		
		if(task==null){
			throw new NullPointerException("job is null!");
		}
		
		log.info("添加一个定时任务："+task.getDescription());
		
		//add to task pool
		jobList.add(task);
		
		log.info("添加成功!");
	}
	
	/**
	 * 删除一个定时任务
	 * @param id
	 * @return
	 */
	public void removeJob(Job job)throws ScheduleException{
		//not allowed to add task when schedule is already running.
		if(running){
			throw new ScheduleException("Schedule is already running,please shutdown Scheduler before adding tasks!");
		}
		jobList.remove(job);
	}
	
	@Override
	public void setTrigger(JobTrigger trigger) {
		this.trigger=trigger;
	}
}
